<template>
  <div class="common-configuration">
    <div class="title font-light font-sans">
      <h2>通用配置</h2>
    </div>
    <Divider />
    <div class="shadow-sl-textGray my-10px w-full h-full">
      <div class="w-500px">
        <Form v-model="commonConfigForm">
          <FormItem label="租户展示名称" class="">
            <EditInput
              :submitApi="updateTenantCommonConfig"
              submitFields="displayName"
              :submitParams="{ tenantCode }"
              @success="fetchCommonInfo"
              :value="tenantDisplayName"
              :powerName="'editTenantName'"
            ></EditInput>
          </FormItem>
          <FormItem label="展示LOGO" class="">
            <div class="common-config-logo mr-20px flex">
              <img v-if="logoUrl" :src="logoUrl" class="card-border flex w-150px h-150px mr-20px" />
              <Upload
                class="block"
                :max-count="1"
                :beforeUpload="beforeUpload"
                v-model:file-list="imageFile"
                :headers="{ 'Content-Type': 'multipart/form-data' }"
                @change="handleFileChange"
                :showUploadList="false"
              >
                <div
                  v-per="'uploadLogo'"
                  class="
                    logo-img
                    cursor-pointer
                    rounded-5px
                    flex
                    justify-center
                    items-center
                    w-150px
                    h-150px
                    bg-sl-uploadBg
                    text-sl-slBlue
                    card-border
                  "
                >
                  <div class="flex justify-center items-center">
                    <PlusOutlined class="text-2xl" />
                  </div>
                  <div class="font-sans">上传LOGO</div>
                </div>
              </Upload>
            </div>
          </FormItem>
        </Form>
      </div>
    </div>
  </div>
  <Divider />
  <div class="domain-configuration">
    <div class="flex justify-between">
      <h2>域名配置</h2>
      <Button
        class="mb-10px"
        v-per="'editDomainConfig'"
        :disabled="disableEditDomainConfig"
        @click="openDomainDrawer"
        type="primary"
        >修改域名配置</Button
      >
    </div>
    <Divider />
    <div class="flex">
      <div class="">
        <Form v-model="dommainConfigForm">
          <FormItem label="租户域名">
            <div class="text-lg">
              <a>{{ domainInfo.name }}</a>
            </div>
          </FormItem>
          <FormItem label="ICP备案号">
            <div class="text-lg">{{ domainInfo.icpRecordNum }}</div>
          </FormItem>
        </Form>
      </div>
    </div>
  </div>
  <Divider />

  <div>
    <div class="flex justify-between">
      <h2>证书配置</h2>
      <Button
        v-per="'updateCertificate'"
        class="float-right"
        type="primary"
        :disabled="!certModifyEnabled"
        @click="openCertDrawer"
        >更新证书</Button
      >
    </div>
    <Divider />
    <Form class="w-800px" v-model="dommainConfigForm">
      <FormItem label="证书配置">
        <div class="text-lg">
          <Button type="primary" v-if="domainInfo.certificateConfStatus === '已配置'" ghost>{{
            domainInfo.certificateConfStatus
          }}</Button>
          <Button type="danger" v-else ghost>{{ domainInfo.certificateConfStatus }}</Button>
        </div>
      </FormItem>
      <FormItem label="证书有效期">
        <div class="text-lg">{{ formattedExpiredTime }}</div>
      </FormItem>
    </Form>
  </div>
  <DomainDrawer @success="handleSuccess('Domain')" :domainName="domainInfo.name" ref="domainDrawerRef" />
  <CertDrawer @success="fetchDomainInfo('Cert')" ref="certDrawerRef" />
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue';
import { Form, FormItem, Upload, Button, Divider } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import DomainDrawer from './components/DomainDrawer.vue';
import CertDrawer from './components/CertDrawer.vue';
import { getTenantCode } from '../../../hooks/globVar/index';
import EditInput from '/@/components/Input/EditInput.vue';
import { useMessage } from '/@/hooks/web/useMessage';
import {
  getTenantCommonConfig,
  getTenantDomainConfig,
  updateTenantCommonConfig,
  updateTenantLogo,
  getCertificateType,
} from '../../../api/system-mgmt/system-config/systemConfig';
import { changeFavicon, changeHTMLTitle } from '../../sys/login/useLogin';
import { useAppSettingStoreWithOut } from '/@/store/modules/appSetting';
import eventBus from '/@/utils/eventBus';

const commonConfigForm = reactive({ name: undefined, logo: undefined });
const dommainConfigForm = reactive({ domain: undefined, ICPLicense: undefined, validityPeriod: undefined });
const imageFile = ref([]);
const domainDrawerRef = ref(null);
const certDrawerRef = ref(null);
const tenantCode = getTenantCode();
const tenantDisplayName = ref<string>(undefined);
const logoUrl = ref<string | undefined>(undefined);
const domainInfo = ref({});
const certModifyEnabled = ref(false);

const { createMessage } = useMessage();

const disableEditDomainConfig = computed(() => {
  // 只有租户可以修改域名，如果modifyEnable为true则可以修改
  return !domainInfo.value.modifyEnabled;
});

const fetchCommonInfo = async () => {
  try {
    const res = await getTenantCommonConfig(tenantCode);
    const appSettingStore = useAppSettingStoreWithOut();
    if (res.displayName) {
      appSettingStore.setTenantName(res.displayName);
      eventBus.emit('resetTenantName');
      changeHTMLTitle(res.displayName);
      tenantDisplayName.value = res.displayName;
      logoUrl.value = res.displayLogo;
    }
  } catch {
    return;
  }
};
const fetchDomainInfo = async () => {
  domainInfo.value = await getTenantDomainConfig(tenantCode);
  domainDrawerRef.value.setDomainForm({ ...domainInfo.value, tenantCode, verify: {} });
  certDrawerRef.value.setCertForm({ ...domainInfo.value.certificate, tenantCode, verify: {} });
  certModifyEnabled.value = domainInfo.value?.certificate?.modifyEnabled;
};

const fetchCertificateType = async () => {
  const res = await getCertificateType();
  domainDrawerRef.value.setCertificateType(res);
  certDrawerRef.value.setCertificateType(res);
};

const openDomainDrawer = () => {
  fetchDomainInfo();
  domainDrawerRef.value.openDrawer();
};
const openCertDrawer = () => {
  fetchDomainInfo();
  certDrawerRef.value.openDrawer();
};

const handleFileChange = async () => {
  try {
    let logo;
    if (imageFile.value.length === 0) {
      return;
    } else {
      logo = imageFile.value[0].originFileObj;
    }
    const res = await updateTenantLogo({ logo, tenantCode });
    if (res.data.code === 0) {
      createMessage.success('LOGO上传成功');
      const appSettingStore = useAppSettingStoreWithOut();
      appSettingStore.setAppLogoPath(res.data.data);
      changeFavicon(res.data.data);
      eventBus.emit('resetLogo');
    } else throw Error(res.data.data);
    await fetchCommonInfo();
    imageFile.value = [];
  } catch (error) {
    createMessage.error('LOGO上传失败');
  }
};
const formattedExpiredTime = computed(() => {
  if (domainInfo.value?.certificate?.expireTime) {
    const date = domainInfo.value.certificate.expireTime.split('T')[0];
    const time = domainInfo.value.certificate.expireTime.split('T')[1].substring(0, 5);
    const formattedDatetime = `${date} ${time}`;
    return formattedDatetime;
  } else {
    return '';
  }
});

const beforeUpload = () => {
  return false;
};

const handleSuccess = (type) => {
  if (type === 'Domain') {
    domainDrawerRef.value.closeDrawer();
    fetchDomainInfo();
  } else {
    certDrawerRef.value.closeDrawer();

    fetchDomainInfo();
  }
};

fetchCommonInfo();
fetchDomainInfo();
fetchCertificateType();
</script>

<style lang="less" scoped>
.domain-configuration {
  .ant-form-item {
    margin-bottom: 10px;
  }
}
</style>
